﻿using System.Modules.ExceptionHanlding;
using System.Text;

namespace System.Modules.Contracts.Attributes
{
    /// <summary>
    /// Encode Property is used as an attribute to set the encoding for a certain property.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class EncodeProperty : Attribute
    {
        Encoding SourceEncoding { get; set; }
        Encoding DestinationEncoding { get; set; }

        /// <summary>
        /// EncodeProperty
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        public EncodeProperty(string source, string destination)
        {
            try
            {
                SourceEncoding = Encoding.GetEncoding(source);
            }
            catch (Exception exception)
            {
                exception.Handle();
            }
            try
            {
                DestinationEncoding = Encoding.GetEncoding(destination);
            }
            catch (Exception exception)
            {
                exception.Handle();
            }
        }

        /// <summary>
        /// EncodeProperty
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        public EncodeProperty(int source, int destination)
        {
            SourceEncoding = Encoding.GetEncoding(source);
            DestinationEncoding = Encoding.GetEncoding(destination);
        }

        /// <summary>
        /// EncodeProperty
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        public EncodeProperty(int source, string destination)
        {
            SourceEncoding = Encoding.GetEncoding(source);
            DestinationEncoding = Encoding.GetEncoding(destination);
        }

        /// <summary>
        /// EncodeProperty
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        public EncodeProperty(string source, int destination)
        {
            SourceEncoding = Encoding.GetEncoding(source);
            DestinationEncoding = Encoding.GetEncoding(destination);
        }

        /// <summary>
        /// Encode | this method do the encoding.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public string Encode(string source)
        {
            if (SourceEncoding != null && DestinationEncoding != null && !String.IsNullOrEmpty(source))
            {
                return DestinationEncoding.GetString(SourceEncoding.GetBytes(source));
            }
            return source;
        }
    }
}
